﻿// ===============================================================================
// XCI.Parent 西安交通信息WinForm开发框架 2019 版权所有
// ===============================================================================

using System;
using System.Threading.Tasks;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;
using XCI.Sys.Filter;
using XCI.Sys.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;

namespace XCI.Sys.Forms
{
    /// <summary>
    /// 系统模块管理
    /// </summary>
    [FormCaption("系统模块管理")]
    public partial class FrmModuleManager : BaseForm
    {
        private readonly ModuleHelper moduleHelper;
        private readonly bool allowSelect = SysApp.Permit("sys.module.select");
        private readonly bool allowInsert = SysApp.Permit("sys.module.insert");
        private readonly bool allowUpdate = SysApp.Permit("sys.module.update");
        private readonly bool allowDelete = SysApp.Permit("sys.module.delete");
        private readonly bool allowExport = SysApp.Permit("sys.module.export");

        public FrmModuleManager()
        {
            InitializeComponent();
            moduleHelper = new ModuleHelper(tree);
            tree.ModelType = typeof(SysModule);
        }

        private async Task LoadAsync()
        {
            await Mutex.EndAsync(() => tree.LoadAsync());
            await moduleHelper.InitAsync(treeImageList);
        }

        /// <summary>
        /// 显示数据编辑
        /// </summary>
        /// <param name="isMenu">是否菜单项</param>
        /// <param name="args">数据编辑参数</param>
        private void ShowEditForm(bool isMenu, EditFormArgs args)
        {
            if (isMenu)
            {
                var editForm = new FrmModuleEdit(args);
                editForm.ShowDialogOk(async () => await LoadAsync());
            }
            else
            {
                var editForm = new FrmPermissionEdit(args);
                editForm.ShowDialogOk(async () => await LoadAsync());
            }
        }

        private async void Form_Load(object sender, EventArgs e)
        {
            WinFormHelper.SetImageListSizeByDpiRatio(treeImageList);
            Mutex.Begin(() => statusCombo.SelectedIndex = 0);
            await LoadAsync();
            moduleHelper.ExpandNode();
        }

        private void Tree_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = moduleHelper.GetModuleImageIndex(e.Node);
        }

        private async void statusCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            await LoadAsync();
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            await LoadAsync();
            tree.ApplyFindFilter(filterEditKey.Text.Trim());
        }

        private async void btnReset_Click(object sender, EventArgs e)
        {
            Mutex.Begin(() => App.ContainerData.SetModel(layoutGroupFilter, SysModuleFilter.Default));
            await LoadAsync();
        }

        private void BtnNewMenu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(true, EditFormArgs.CreateTree(tree.SelectedId));
        }

        private void BtnNewPermission_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowEditForm(false, EditFormArgs.CreateTree(tree.SelectedId));
        }

        private void BtnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var selected = (SysModule)tree.Selected;
            ShowEditForm(!selected.IsPermission, EditFormArgs.EditTree(tree.SelectedId, selected.ParentId));
        }

        private async void BtnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowWarnYesNo("确定要复制当前选中的数据吗?") != System.Windows.Forms.DialogResult.Yes) return;
            await SysModuleService.Instance.CopyAsync(tree.SelectedId);
            await tree.LoadAsync();
        }

        private async void BtnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            await tree.DeleteCheckedAsync();
        }

        private async void BtnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var filter = tree.GetFilter();
            await App.Excel.ExportFileDialogAsync((path, fields) => SysModuleService.Instance.ExportAsync(path, filter as SysModuleFilter), "系统模块列表", this);
        }

        private void BtnProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new FrmModuleDetails(tree).ShowDialogOk();
        }

        private async void BtnAddStandardPermission_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBoxHelper.ShowWarnYesNo("确定要给当前模块添加标准按钮吗?") != System.Windows.Forms.DialogResult.Yes) return;
            await SysModuleService.Instance.SaveStandardPermissionAsync(tree.Selected as SysModule);
            await LoadAsync();
            MessageBoxHelper.ShowMessage("标准按钮添加成功");
        }

        private async void RepositoryEditUpdate_CheckedChanged(object sender, EventArgs e)
        {
            var edit = tree.ActiveEditor;
            var col = tree.FocusedColumn;
            var field = StringHelper.HumpToLine(col.FieldName);
            await SysModuleService.Instance.UpdateField(tree.SelectedId, field, edit.EditValue.ToBool());
        }

        private async void RepositoryEditStatus_CheckedChanged(object sender, EventArgs e)
        {
            var edit = tree.ActiveEditor;
            var col = tree.FocusedColumn;
            if (col.FieldName.Equals(nameof(SysModule.Status)))
            {
                await SysModuleService.Instance.UpdateStatusAsync(tree.SelectedId, edit.EditValue.ToBool());
            }
        }

        private void tree_LoadData(object sender, LoadTreeDataEventArgs e)
        {
            e.Task = async () => await SysModuleService.Instance.SelectListAsync(e.Filter as SysModuleFilter);
        }

        private void tree_DetectFilter(object sender, DetectTreeFilterObjectEventArgs e)
        {
            e.Filter = App.ContainerData.GetModel(layoutGroupFilter, new SysModuleFilter());
        }

        private void tree_DeleteData(object sender, DeleteDataEventArgs e)
        {
            e.Task = () => SysModuleService.Instance.DeleteAsync(tree.CheckedIds);
        }

        private async void tree_NodeDragChangedChanged(object sender, NodeDragChangedEventArgs e)
        {
            await SysModuleService.Instance.UpdateDndAsync(e.ChangedData);
        }

        private void tree_RowSelectionChanged(object sender, EventArgs e)
        {
            var isSingle = !tree.HasMultiSelected && !tree.HasMultiChecked && tree.HasSelected;
            btnEdit.Enabled = isSingle && allowUpdate;
            btnCopy.Enabled = isSingle && allowInsert;
            btnDelete.Enabled = tree.HasChecked && allowDelete;
            btnExport.Enabled = tree.HasData && allowExport;
            btnProperty.Enabled = isSingle;

            var selected = tree.Selected as SysModule;
            //除了权限下面不能建菜单,其他都可以
            var showNewMenu = !(tree.HasSelected && selected != null && selected.IsPermission) && allowInsert;
            var showNewPermission = allowInsert;
            //只有菜单下面才能新建标准权限项
            var showAddStandardPermission = showNewPermission && tree.HasSelected && selected != null && !selected.IsPermission;

            btnNewMenu.Visibility = WinFormHelper.BarItemVisible(showNewMenu);
            btnNewPermission.Visibility = WinFormHelper.BarItemVisible(showNewPermission);
            btnAddStandardPermission.Visibility = WinFormHelper.BarItemVisible(showAddStandardPermission);
        }

    }
}